import os, pickle

def write_dict():  # 在硬盘初始化一个空字典(创建表)
    if os.path.exists("/tmp/user.data") == False:
        userdb = {}  # 空字典: 用于保存用户信息
        with open("/tmp/user.data", mode="wb") as fw:
            pickle.dump(userdb, fw)  # 持久化空字典


def login():
    username = input("username: ")
    password = input("password: ")
    # 获取磁盘中的字典数据 pickle.load()
    with open("/tmp/user.data", mode="rb") as fr:
        userdb = pickle.load(fr)
    if username in userdb and password == userdb[username]:
        print("login ok~")
    else:
        print("用户名或密码错误~")




def register():
    username = input("username: ").strip()
    # 获取磁盘中的字典数据 pickle.load()
    with open("/tmp/user.data", mode="rb") as fr:
        userdb = pickle.load(fr)
    if username and username not in userdb:
    # if username != "" and username not in userdb.keys(): # in userdb
        password = input("password: ")  # 用户名可用, 再设置密码
        userdb[username] = password  # 将数据添加到字典中
        # 将修改后的字典写回到磁盘
        with open("/tmp/user.data", mode="wb") as fw:
            pickle.dump(userdb, fw)
    else:
        print("注册失败")






def show_menu():
    write_dict()  # 调用初始化字典函数
    while True:
        welcome = """欢迎!!!请按照下列提示,选择要执行的任务:
(1)注册
(2)登录
(3)退出, 请选择:  """
        xz = input(welcome)
        if xz not in ["1", "2", "3"]:
            print("请按照提示重新输入!!!")
            continue
        elif xz == "1":
            register()  # 调用注册函数
        elif xz == "2":
            login()
        else:
            print("byebye~")
            break
if __name__ == '__main__':
    show_menu()


